package com.kanshu.ksgb.fastread.doudou.module.download.utils;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.reflect.TypeToken;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.CacheManager;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.common.util.JsonUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ThreadPoolUtil;
import com.kanshu.ksgb.fastread.doudou.module.download.bean.DownLoadChapterBean;
import com.kanshu.ksgb.fastread.doudou.module.download.event.DeleteDownLoadEvent;
import com.kanshu.ksgb.fastread.doudou.module.download.service.DownloadBookService;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;

/**
 * Created by xubo on 2018/12/4
 */

public class DownLoadHelper {

    /**
     * 清除某本书 下载内容
     */
    public static synchronized void clearDownLoadBook(String bookId) {
        try {
            String cacheDir = CacheManager.getInstance().getPathDataTxt() + bookId;
            // 重置本书下载章节数量
            MMKVUserManager.getInstance().saveBookDownloadChapterCount(bookId, 0);
            // 删除书籍下载内容
            deleteDownLoadFile(cacheDir);
            // 删除完毕，刷新UI
            EventBus.getDefault().post(new DeleteDownLoadEvent());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除用户所有下载内容
     */
    public static synchronized void clearAllDownLoadBook() {
        try {
            String dataTextPath = CacheManager.getInstance().getPathDataTxt();
            File dataTextFile = new File(dataTextPath);
            if (dataTextFile.isDirectory()) {
                File files[] = dataTextFile.listFiles();
                if(files != null) {
                    for (File file : files) {
                        // 删除SD书籍下载内容
                        deleteDownLoadFile(file.getPath());
                    }
                }
            }
            // 清空完毕，刷新UI
            EventBus.getDefault().post(new DeleteDownLoadEvent());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重新下载失败章节
     * @return 重新下载章节数量
     */
    public static int againDownload(Context context, String mBookId){
        int selectCount = 0;
        DownloadBookService.reSetCurrentProgress(mBookId);
        String failChapter = MMKVUserManager.getInstance().getDownLoadFailGroupId(mBookId);
        List<DownLoadChapterBean> fillDownLoadList = JsonUtils.json2Bean(failChapter, new TypeToken<List<DownLoadChapterBean>>(){}.getType());
        for(DownLoadChapterBean bean : fillDownLoadList){
            if(bean != null && !TextUtils.isEmpty(bean.id)) {
                bean.chapters = JsonUtils.json2Bean(MMKVUserManager.getInstance().getDownLoadFailChapter(mBookId, bean.id), new TypeToken<List<DownLoadChapterBean>>() {
                }.getType());
                if (!com.kanshu.ksgb.fastread.doudou.common.util.Utils.isEmptyList(bean.chapters)) {
                    bean.book_id = mBookId;
                    selectCount += bean.chapters.size();
                    DownloadBookService.checkServiceAndPostEvent(context, bean);
                    MMKVUserManager.getInstance().reSetDownLoadFailChapter(mBookId, bean.id);
                }
            }
        }
        MMKVUserManager.getInstance().reSetDownLoadFailGroupId(mBookId);
        return selectCount;
    }

    /**
     * 删除文件夹内的书籍下载文件
     *
     * @param filePath
     * @return
     */
    private static void deleteDownLoadFile(String filePath) {
        ThreadPoolUtil.getInstance().addTask(() -> {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    File files[] = file.listFiles();
                    if(files != null && files.length > 0) {
                        for (File file1 : files) {
                            if(file1.getPath().endsWith("download.txt")) {
                                file1.delete();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
